package com.example.iterator;

public class CustomArray<E> implements Iterable<E> {
    private static final int INITIAL_CAP = 10;
    private Object[] elements;
    private int size;

    public CustomArray() {
        elements = new Object[INITIAL_CAP];
    }

    public void add(Object e) {
        elements[size++] = e;
    }

    public E remove(int idx) {
        if (idx < 0)
            throw new IndexOutOfBoundsException();
        Object ret = elements[idx];
        System.arraycopy(elements, idx+1, elements, idx, size-idx-1);
        size--;
        elements[size] = null;
        return (E) ret;
    }

    public int size() {
        return size;
    }

    @Override
    public Iterator<E> iterator() {
        return new Itr();
    }

    final class Itr<E> implements Iterator<E> {
        int cursor;
        int last = -1;

        @Override
        public boolean hasNext() {
            return cursor < size;
        }

        @Override
        public E next() {
            if (!hasNext())
                throw new IllegalStateException();
            Object obj = elements[cursor];
            last = cursor;
            cursor++;
            return (E) obj;
        }

        @Override
        public void remove() {
            if (last < 0)
                return;
            CustomArray.this.remove(last);
            cursor = last;
            last = -1;
        }
    }
}
